import { 
	saveStringToFile
 } from "../utils/util";
 import { USER_FILE_NAME } from "../constant/constant";

var serverUrl = "https://www.oschina.net";
var appToken = "ccbf55b0eb2c55fd31634585b7f856aa9d9067e4";
var cookieStr = "";
// var serverUrl = "https://api.apiopen.top";
// 请求头处理函数
function createHeader(url, type) {
	let header = {}
	if (type == 'POST_PARAMS') {
		header = {
			'content-type': 'application/json',
			// 'content-type': 'application/json;charset=UTF-8',
		}
	} else {
		header = {
			'content-type': 'application/x-www-form-urlencoded;charset=utf-8',
			// 'content-type': 'application/json;charset=UTF-8',
		}
	}
	header['AppToken'] = appToken;
	if(cookieStr.length == 0){
		cookieStr = getApp().globalData.cookieStr;
		// cookieStr = wx.getStorageSync('cookie');
	}
	header['Cookie'] = cookieStr;
	// if (exceptionAddrArr.indexOf(url) == -1) { //排除请求的地址不需要token的地址
	// 	let token = wx.getStorageSync("authorize_token");
	// 	header['access-token'] = token;
	// }
	return header;
}
//post请求，数据在body中
function postRequest(url, data) {
	let header = createHeader(url, 'POST');
	return new Promise((resolve, reject) => {
		wx.request({
			url: serverUrl + url,
			data: data,
			header: header,
			method: 'POST',
			success: (res => {
				console.log('statusCode='+res.statusCode+', errMsg='+res.errMsg)
				if (res.statusCode === 200) {
					console.log('code='+res.data.code+', message='+res.data.message)
					console.log('result='+res.data.result)
					//200: 服务端业务处理正常结束
					if((url.search('apiv2/account_login') >= 0 || url.search('apiv2/account_register') >= 0) && res.data.code == 1){
						var app = getApp();
						var result = res.data.result;
						var userId = result.id;
      			app.globalData.isLogin = true;
						app.globalData.userInfo = result;
						app.globalData.userId = userId;
						try {
							wx.setStorageSync('userId', userId);
						} catch (error) {
							console.log(error);
						}
						var cookies = res.cookies;
						cookies.forEach(cooki => {
							if(cooki.startsWith('oscid')){
								var oscid = cooki.substring(0, cooki.indexOf(';'));
								if(oscid.length>20){
									cookieStr = cooki;
									wx.setStorageSync('cookie', cooki);
									saveStringToFile('userId='+userId+';cookie='+cooki, USER_FILE_NAME);
								}
							}
						});
					}
					resolve(res)
				} else {
					reject(res)
					console.log('statusCode='+res.statusCode+', errMsg='+res.errMsg)
				}
			}),
			fail: (res => {
				reject(res)
				console.log('err='+res.detail)
			})
		})
	})
}
//post请求，数据按照query方式传给后端
function postParamsRequest(url, data) {
	let header = createHeader(url, 'POST_PARAMS');
	let useurl = url;
	return new Promise((resolve, reject) => {
		wx.request({
			url: serverUrl + useurl,
			data: data,
			header: header,
			method: 'POST',
			success: (res => {
				console.log('statusCode='+res.statusCode+', errMsg='+res.errMsg)
				if (res.statusCode === 200) {
					//200: 服务端业务处理正常结束
					console.log('code='+res.data.code+', message='+res.data.message)
					console.log('result='+res.data.result)
					resolve(res)
				} else {
					reject(res)
					console.log('statusCode='+res.statusCode+', errMsg='+res.errMsg)
				}
			}),
			fail: (res => {
				reject(res)
				console.log('err='+res.detail)
			})
		})
	})
}
//get 请求
function getRequest(url, data) {
	let header = createHeader(url, 'GET');
	return new Promise((resolve, reject) => {
		wx.request({
			url: serverUrl + url,
			data: data,
			header: header,
			method: 'GET',
			success: (res => {
				console.log('statusCode='+res.statusCode+', errMsg='+res.errMsg)
				if (res.statusCode === 200) {
					//200: 服务端业务处理正常结束
					console.log('code='+res.data.code+', message='+res.data.message)
					console.log('result='+res.data.result)
					resolve(res)
				} else {
					reject(res)
					console.log('statusCode='+res.statusCode+', errMsg='+res.errMsg)
				}
			}),
			fail: (res => {
				reject(res)
				console.log('err='+res.detail)
			})
		})
	})
}
//put请求
function putRequest(url, data) {
	let header = createHeader(url, 'PUT');
	return new Promise((resolve, reject) => {
		wx.request({
			url: serverUrl + url,
			data: data,
			header: header,
			method: 'PUT',
			success: (res => {
				if (res.statusCode === 200) {
					//200: 服务端业务处理正常结束
					resolve(res)
				} else {
					reject(res)
				}
			}),
			fail: (res => {
				reject(res)
			})
		})
	})
}
//delete请求
function deleteRequest(url, data) {
	let header = createHeader(url, 'DELETE');
	return new Promise((resolve, reject) => {
		wx.request({
			url: serverUrl + url,
			data: data,
			header: header,
			method: 'DELETE',
			success: (res => {
				console.log('statusCode='+res.statusCode+', errMsg='+res.errMsg)
				if (res.statusCode === 200) {
					console.log('code='+res.data.code+', message='+res.data.message)
					console.log('result='+res.data.result)
					//200: 服务端业务处理正常结束
					resolve(res)
				} else {
					reject(res)
				}
			}),
			fail: (res => {
				reject(res)
			})
		})
	})
}

 /**
 * 封装wx.request请求
 * method： 请求方式
 * url: 请求地址
 * data： 要传递的参数
 * callback： 请求成功回调函数
 * errFun： 请求失败回调函数
 **/
function wxRequest(url, method, data, callback, errFun, completeFun) {
  wx.request({
   url: url,
   method: method,
   data: data,
   header: {
    'content-type': method == 'GET'?'application/json':'application/x-www-form-urlencoded',
    'Accept': 'application/json'
   },
   dataType: 'json',
   success: function (res) {
    callback(res.data);
   },
   fail: function (err) {
    errFun(res);
   },
   complete: function(end){
      completeFun(end);
   }
  })
 }

module.exports.getRequest = getRequest;
module.exports.postRequest = postRequest;
module.exports.postParamsRequest = postParamsRequest;
module.exports.putRequest = putRequest;
module.exports.deleteRequest = deleteRequest;
module.exports.wxRequest = wxRequest;